import akshare as ak
import pandas as pd
import talib
import numpy as np

def get_hs300_data():
    # 获取沪深300指数数据
    hs300 = ak.stock_zh_index_daily(symbol="sh000300")
    hs300['date'] = pd.to_datetime(hs300['date'])
    hs300.set_index('date', inplace=True)

    # 计算牛熊分界线（年线）
    hs300['ma250'] = hs300['close'].rolling(250).mean()
    hs300['bull_market'] = hs300['close'] > hs300['ma250']  # 收盘价高于年线为牛市
    return hs300
    

def get_qing_xu():
    # 获取每日涨跌家数
    market_data = ak.stock_a_all_market()
    bullish = market_data[market_data['price_change'] > 0].shape[0]
    bearish = market_data[market_data['price_change'] < 0].shape[0]

    # 情绪指标 = 涨停占比 + 量比因子 + VIX波动率因子
    vix = ak.stock_hk_vix()  # 港股VIX替代A股恐慌指数
    vix_latest = vix.iloc[-1]['close'] / 50  # 归一化处理

    emotion_score = (
        (market_data[market_data['change_percent'] >= 9.9].shape[0] / len(market_data)) * 0.4 +
        (np.mean(market_data['turnover_rate']) / 3) * 0.3 +  # 量比因子简化
        min(vix_latest, 0.7) * 0.3
    ) * 100
    print(f"涨停家数：{bullish}只，跌停家数：{bearish}只，情绪指标：{emotion_score:.2f}%")

# 获取实时大盘数据
def get_index_data():
    df_sh = ak.stock_zh_index_daily(symbol="sh000001")  # 上证指数
    df_sz = ak.stock_zh_index_daily(symbol="sz399001")  # 深证成指
    return pd.concat([df_sh, df_sz])

# 获取板块数据
def get_industry_data():
    return ak.stock_board_industry_hist_em()  # 行业板块历史行情

# 获取个股实时数据（含量比、涨跌幅等）
def get_stock_spot_data():
    return ak.stock_zh_a_spot_em()

# 获取涨停板信息
def get_limit_up_stocks(trade_date):
    df = ak.stock_zt_pool_em(date=trade_date)
    return df

# # 示例：获取2023年10月10日的涨停板信息
# trade_date = '20241030'
# limit_up_stocks = get_limit_up_stocks(trade_date)

# 打印涨停板信息
# print(limit_up_stocks)

def calculate_market_sentiment(df_index):
    # 技术情绪：量比+波动率+RSI
    df_index['vol_ratio'] = df_index['volume'] / df_index['volume'].rolling(20).mean()
    df_index['atr'] = talib.ATR(df_index['high'], df_index['low'], df_index['close'], timeperiod=14)
    df_index['rsi'] = talib.RSI(df_index['close'], timeperiod=14)
    technical_score = (df_index['vol_ratio'] + df_index['atr'] + df_index['rsi']/100).mean()
    
    # 资金情绪：主力净流入率+融资余额
    capital_flow = ak.stock_money_flow_industry()  # 行业资金流
    capital_score = capital_flow['net_inflow_rate'].mean()
    
    # 综合情绪（0-100分）
    sentiment_score = 0.4*technical_score + 0.6*capital_score
    return min(max(sentiment_score*20, 0), 100)  # 标准化

import akshare as ak
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings("ignore")

# 步骤1：获取大盘数据并计算情绪指标
def get_market_sentiment():
    # 获取沪深300指数作为大盘指标
    market_data = ak.stock_zh_index_daily(symbol="sh000300")
    market_data.index = pd.to_datetime(market_data['date'])
    market_data = market_data.sort_index()
    
    # 计算情绪指标（20日收益率）
    market_data['20d_return'] = market_data['close'].pct_change(20)
    return market_data[['date', 'close', '20d_return']]

if __name__ == '__main__':
    print(ak.__version__   );
    hs300_data=get_hs300_data()
    # print(hs300_data.tail())
    # get_qing_xu()
    # index_data = get_index_data()
    # print(index_data.tail())
    market_data=get_market_sentiment()
    print(market_data.tail())